﻿#include "widget.h"
#include "ui_widget.h"
#include <QDebug>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    Init();
}

Widget::~Widget()
{
    delete ui;
    for(int i = 0; i < LabelList.size(); i++) {
        delete LabelList.at(i).Label;
    }
    LabelList.clear();
}

void Widget::Init()
{
    QImage Img;
    Img.load("D:\\Demo\\Qt\\ImageDemo\\verf.png");
//    Img.load("D:\\Demo\\Qt\\ImageDemo\\trainico.jpg");
    ui->label->setPixmap(QPixmap::fromImage(Img));
}

void Widget::mousePressEvent(QMouseEvent *e)
{
    if(e->button() == Qt::LeftButton) {
        qDebug() << "x = " << e->pos().rx() << ", y = " << e->pos().ry();
        bool IsExist = false;
        for(int i = 0; i < LabelList.size(); i++) {
            qDebug() << i << "; " << LabelList.at(i).X - 10 << ", " << LabelList.at(i).X + 10 << "; " <<
                        LabelList.at(i).Y - 10 << ", " << LabelList.at(i).Y + 10;
            if((e->pos().rx() >= LabelList.at(i).X - 10) && (e->pos().rx() <= LabelList.at(i).X + 10) &&
                    (e->pos().ry() >= LabelList.at(i).Y - 10) && (e->pos().ry() <= LabelList.at(i).Y + 10)) {
                IsExist = true;
                LabelList.at(i).Label->hide();
                delete LabelList.at(i).Label;
                LabelList.remove(i);
                break;
            }
        }
        if(!IsExist) {
            SelectPic Pic;
            QLabel *Label = new QLabel(this);
            QImage Img;
            Img.load("D:\\Demo\\Qt\\ImageDemo\\trainico.jpg");
            Label->setPixmap(QPixmap::fromImage(Img));
            Label->setGeometry(e->pos().rx() - 10, e->pos().ry() - 10, 20, 20);
            Label->show();
            Pic.Label = Label;
            Pic.X = e->pos().rx();
            Pic.Y = e->pos().ry();
            LabelList.push_back(Pic);
            qDebug() << "Button click..";
        }
    }
}
